<template>
	<div class="cart">
		<van-nav-bar title="购物车" left-text="返回" right-text="我的" left-arrow @click-left="onClickLeft" @click-right="onClickRight" />
		<van-swipe-cell v-for="item in carts" :key="item.id">
			<van-card :price="item.product.price.toFixed(2)" :title="item.product.name" :thumb="item.product.coverImage | dalImg">
				<template #tag>
					<van-checkbox v-model="item.checked"></van-checkbox>
				</template>
				<template #footer>
					<van-stepper v-model="item.amount" integer disable-input @plus="cartplus(item)" @minus="cartMinus(item)" />
				</template>
			</van-card>
			<template #right>
				<van-button square type="danger" text="删除" class="delete-button" @click="delFromCarHandle(item.id)" />
			</template>
		</van-swipe-cell>
		<van-submit-bar :price="sumPrice" button-text="提交订单" @submit="onSubmit">
			<van-checkbox v-model="checked">全选</van-checkbox>
			<!-- <template #tip>
				你的收货地址不支持同城送,
				<span @click="onClickEditAddress">修改地址</span>
			</template> -->
		</van-submit-bar>
	</div>
</template>

<script>
import { loadCartsAPI, addToCarAPI, delFromCarAPI } from '../services/carts';
export default {
	name: 'Cart',
	data() {
		return {
			carts: []
		};
	},
	created() {
		this.loadData();
	},
	methods: {
		async loadData() {
			const res = await loadCartsAPI();
			this.carts = res.data
				.filter(item => item.product)
				.map(item => {
					return {
						...item,
						checked: false
					};
				});
                  // 获取用户购物车的数量
                 this.$eventBus.$emit("updateCartCount");
		},
		async cartplus(item) {
			await addToCarAPI(item.product.id, 1);
             //获取购车数量
			this.$eventBus.$emit("updateCartCount");
		},
		async cartMinus(item) {
			await addToCarAPI(item.product.id, -1);
            //获取购车数量
			this.$eventBus.$emit("updateCartCount");
		},
		async delFromCarHandle(id) {
			await delFromCarAPI(id);
			this.loadData();
             //获取购车数量
			this.$eventBus.$emit("updateCartCount");
		},
		onClickLeft() {
			this.$router.go(-1);
		},
		onClickRight() {
			this.$router.push({
				name: 'User'
			});
		},
		onSubmit() {
            this.$router.push({
                name:'SubOrder'
            })
        }
	},
	computed: {
		checked: {
			set(v) {
				this.carts.forEach(item => (item.checked = v));
			},
			get() {
				return this.carts.every(item => item.checked);
			}
		},
		sumPrice() {
			return this.carts.filter(item => item.checked).reduce((pre, cur) => pre + cur.price * cur.amount, 0) * 100;
		}
	}
};
</script>

<style scoped="scoped" lang="scss">
.delete-button {
	height: 100%;
}
</style>
